package com.wider.controller;


import cn.hutool.core.thread.ThreadUtil;
import com.opencsv.CSVReader;
import com.opencsv.CSVReaderBuilder;
import com.opencsv.exceptions.CsvException;
import com.opencsv.exceptions.CsvValidationException;
import com.wider.mapper.BaseDataMapper;
import com.wider.pojo.BaseData;
import com.wider.services.BaseDataService;
import com.wider.services.FlowServices;
import com.wider.services.impl.FlowServicesImpl;
import com.wider.utils.U;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.lang3.ThreadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import javax.xml.transform.Result;
import java.io.*;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

/**
 * @author lie
 */
@RestController
@RequestMapping("file")
public class FileController {

    @Autowired
    private BaseDataService baseDataService;
    @Autowired
    private FlowServices flowServices;


    @PostMapping("/upload/csv")
    public ResponseEntity<?> processCSVFile(@RequestParam("file") MultipartFile file) {

        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("Please select a file to upload");
        }
        String originalFilename1 = file.getOriginalFilename();
        String originalFilename = originalFilename1.substring(0, originalFilename1.length() - 4);

        List<BaseData> baseDataList = new ArrayList<>();
        try (InputStream inputStream = file.getInputStream();
             InputStreamReader reader = new InputStreamReader(inputStream);
             CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT.withFirstRecordAsHeader())) {

            List<CSVRecord> records = csvParser.getRecords();
            boolean isOne = true;
            for (CSVRecord record : records) {
                // 根据实际情况对记录进行业务逻辑处理
                BaseData baseData = new BaseData();
                if (isOne) {
                    isOne = !isOne;

                    continue;
                }
                try {
                    DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
                    LocalDateTime localDateTime = LocalDateTime.parse(record.get(0), formatter);
                    baseData.setDate(localDateTime);
                    baseData.setData(new BigDecimal(record.get(1)));
                    if (baseData.getData() != null && baseData.getDate() != null) {
                        baseDataList.add(baseData);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            flowServices.ddlRunner(originalFilename);
            if (!FlowServicesImpl.processingCaseNameList.contains(originalFilename)) {
                flowServices.ddlRunner(originalFilename);
                while (!baseDataList.isEmpty()) {
                    if (!baseDataService.insertBatchT(baseDataList.subList(0, 10000), originalFilename)) {
                        return ResponseEntity.ok("CSV file processed error,maybe you can check the database");
                    }
                    baseDataList.subList(0, 10000).clear();
                }
                U.cachedThreadPool.execute(() -> {
                    flowServices.processingData(originalFilename);
                });
                return ResponseEntity.ok("CSV file processed success");

            } else {
                return ResponseEntity.ok("The same name task is running ,please commit it later or restart this application and commit this file again");
            }

        } catch (Exception e) {
            return ResponseEntity.badRequest().body("Error occurred while processing the CSV file: " + e.getMessage());
        }
    }

    @PostMapping("/upload/csv/stream/{caseName}")
    public String handleLargeFileUpload(HttpServletRequest request, @PathVariable String caseName) throws IOException, CsvValidationException {
        System.out.println("caseName" + caseName + "已经开始运行");
        InputStream inputStream = request.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
        CSVReader csvReader = new CSVReaderBuilder(reader).build();
        String[] strings = csvReader.readNext();
        List<BaseData> baseDataList = new ArrayList<>();
        if (!FlowServicesImpl.processingCaseNameList.contains(caseName)) {
            flowServices.ddlRunner(caseName);
            while (null != strings) {
                // 根据实际情况对记录进行业务逻辑处理
                BaseData baseData = new BaseData();
                if ("date".equals(strings[0]) && "data".equals(strings[1])) {
                    strings = csvReader.readNext();
                    continue;
                }
                try {
                    DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
                    LocalDateTime localDateTime = LocalDateTime.parse(strings[0], formatter);
                    baseData.setDate(localDateTime);
                    baseData.setData(new BigDecimal(strings[1]));
                    if (baseData.getData() != null && baseData.getDate() != null) {
                        baseDataList.add(baseData);
                        if (baseDataList.size() > 10000) {
                            baseDataService.insertBatchT(baseDataList, caseName);
                            baseDataList.clear();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    System.err.println("caseName" + caseName + "exception message : " + e.getMessage());
                }
                strings = csvReader.readNext();
            }
            if (!baseDataList.isEmpty()) {
                baseDataService.insertBatchT(baseDataList, caseName);
                baseDataList.clear();
            }
            U.cachedThreadPool.execute(() -> {
                flowServices.processingData(caseName);
            });
            csvReader.close();
            return "insert success!";
        }
        return "insert fail,because the same name task is running,please commit it later";
    }

    @PostMapping("/upload/csv/memory/{caseName}")
    public String streamUploadFile(HttpServletRequest request, @PathVariable String caseName) throws IOException, CsvValidationException {
        System.out.println("caseName" + caseName + "已经开始运行");

        InputStream inputStream = request.getInputStream();

        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));

        CSVReader csvReader = new CSVReaderBuilder(reader).build();

        String[] strings = csvReader.readNext();
        List<BaseData> baseDataList = new ArrayList<>();
        int i = 0;

        while (null != strings) {
            BaseData baseData = new BaseData();
            if ("date".equals(strings[0]) && "data".equals(strings[1])) {
                strings = csvReader.readNext();
                continue;
            }
            try {
                DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
                LocalDateTime localDateTime = LocalDateTime.parse(strings[0], formatter);
                baseData.setDate(localDateTime);
                baseData.setData(new BigDecimal(strings[1]));
                if (baseData.getData() != null && baseData.getDate() != null) {
                    baseDataList.add(baseData);
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.err.println("caseName" + caseName + "exception message : " + e.getMessage());
            }
            strings = csvReader.readNext();
        }

        flowServices.processingDatas(baseDataList,caseName);
        csvReader.close();
        return "";
    }

    @PostMapping("/test1/{caseName}")
    public void tester(@PathVariable String caseName, HttpServletRequest request) throws IOException {
        InputStream inputStream = request.getInputStream();

        // 创建一个BufferedReader用于逐行读取数据
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

        // 定义CSV格式，例如默认格式，并根据实际情况选择是否包含表头
        CSVFormat csvFormat = CSVFormat.DEFAULT.withFirstRecordAsHeader();

        // 创建CSVParser以流式方式解析数据
        CSVParser csvParser = new CSVParser(reader, csvFormat);

        try {
            // 逐行处理CSV记录
            for (CSVRecord record : csvParser) {
                // 在这里处理每一行数据
//                processSingleRecord(record);
            }
        } finally {
            // 确保关闭资源
            csvParser.close();
            reader.close();
            inputStream.close();
        }
    }

    @PostMapping("/test2/{caseName}")
    public void tester2(@PathVariable String caseName, HttpServletRequest request) throws IOException {
        InputStream inputStream = request.getInputStream();

        byte[] buf = new byte[4096];

        inputStream.read(buf);

        String str = new String(buf, "gb2312");

        System.out.println(str);


    }
}
